import React from 'react';
import {inject, observer} from 'mobx-react';
import { Flex, Icon, Button, Toast, Picker, RichEditor, Avatar, TextareaItem, VoiceToText,Checkbox, List, Switch} from 'weaver-mobile';
import {Upload,CKRichText} from 'weaver-mobile-page';
import base from "../../util/base";
import {_} from "../../util/pcPublic";
import {getLabel} from "../../util/common";
import {withRouter} from 'react-router-dom';
import IconBtnsList from './IconBtnsList';
import SoundToWord from './SoundToWord';
import SignMore from './SignMore';
import RemindType from '../hoverRoute/remind/RemindType';
import {BrowserHrm} from 'weaver-mobile-page';
import * as SignUtil from '../../util/SignUtil';
import * as VariableKeys from '../../constants/variableKey';
import * as EmSDK from '../../util/emSDK';
import * as AdapterConstant from "../../constants/adapter";
import {toJS} from "mobx";

const CKRichEditor = CKRichText.CKRichEditor;
const CheckboxItem = Checkbox.CheckboxItem;

@inject('wfSignInputStore','wfRemindStore')
@withRouter
@observer
class SignActionPanel extends React.Component {

    constructor(props) {
        super();
        this.rickEditorRef = React.createRef();
        this.state = {
            isCheckMore: false //是否选中“更多”按钮
        }
    }

    componentDidMount() {
        const { wfSignInputStore,wfRemindStore, location = {}} = this.props;
        const { pathname } = location;
        wfSignInputStore.setNowPathName(pathname)
        wfSignInputStore.initAtData();
        const { changeRemindType, defaultRemindSet} = wfRemindStore;
        changeRemindType(defaultRemindSet, true); //将流程提醒设置改成默认
        if(!wfSignInputStore.havetsValue) {
          this.initEndTakOverTimeParams();
        }
    }
 
    componentWillUnmount() {
      const { wfRemindStore, wfSignInputStore:{clearSetStatus} } = base.allStores;
      const { changeRemindType, defaultRemindSet} = wfRemindStore;
      changeRemindType(defaultRemindSet, true); //将流程提醒设置改成默认
      clearSetStatus();
    }
    render() {
        const {wfSignInputStore} = this.props;
        const { hiddenSignInput, isShowIconBtnList,replyNoticeInfo,fowardSubmitParams={}} = wfSignInputStore;
        const { showReplyNotice,noticeLabel } =  replyNoticeInfo;
        const {isHideInput = '0'} = base.wfGlobalStore.commonParam || {};
        const {forwardflag} = fowardSubmitParams;
        const showAttachment = SignUtil.getVariableMapVal(VariableKeys.SHOW_MORE_FUN, false);
        const signVoiceEntry = SignUtil.getVariableMapVal(VariableKeys.SIGN_VOICE_ENTRY, false);
        const signImgUpload = SignUtil.getVariableMapVal(VariableKeys.SIGN_IMG_UPLOAD, false);
        return (
            <div className='wf-signView-panel'
                 style={{'bottom': SignUtil.calcReqMainPaadingBottom()}}>
                <div className='wf-signView-panel-mask'
                    onClick={() => {
                        const { cancleCallback } = this.props;
                        if (typeof cancleCallback === 'function') {
                            cancleCallback();
                        } else {
                            hiddenSignInput();
                        }
                    }}>
                </div>
                <div className='wf-signView-panel-content'>
                    {this.getSignPanelTitle(isHideInput)}
                    {this.state.isCheckMore && this.getSignSetting()}
                    {this.getRemarkQuoteCom()}
                    {isHideInput != '1' &&
                        <div className={`sign-panel-main ${this.judgeIsRichText() ? "sign-panel-richtext" : "sign-panel-textarea"}`}>
                            {this.getRemarkEditor()}
                            {this.getLocationInfo()}
                        </div>
                    }
                    {showReplyNotice == 1 && forwardflag == '1' && this.getReplyNoticeComp(noticeLabel)}
                    {isShowIconBtnList && <IconBtnsList/>}
                </div>
                {signVoiceEntry && <VoiceToText
                    style={{ width: "100%", height: "200px", borderRadius: "0" }}
                    onChange={this.voiceToText}
                />}
                {signImgUpload && this.getImgUploadCom()}
                {showAttachment && <SignMore/>}
                {this.getDisplayCom()}
            </div>
        )
    }

    /**
     *
     * @returns {boolean}
     */
    getReplyNoticeComp = (noticeLabel)=>{
        const {wfSignInputStore} = this.props;
        const replyNotice =  wfSignInputStore.replyNoticeInfo.replyNotice == 1 ? true : false;
        return (<div className = "reply-notice-div"><CheckboxItem key="1" defaultChecked={replyNotice} onChange={(i)=>{

                    wfSignInputStore.setForwardParams({isShowReplyNotice: i.target.checked?1:0});
                } }>
                    { noticeLabel }
                </CheckboxItem></div>
             );
    }

    voiceToText = (res) => {
        const wfOperateStore = base.wfOperateStore;
        const { markInfo = {}} = wfOperateStore;
        const { extendParams = {}} = toJS(markInfo);
        const { mobileSignInputRichText = false} = extendParams;
        const { wfSignInputStore } = this.props;
        const { isForwad, controlVariableMap,ckStore} = wfSignInputStore;
        const remarkKey = isForwad ? VariableKeys.FORWARD_SIGN_CONTENT : VariableKeys.SIGN_CONTENT;
        let soundDatas = SignUtil.getVariableMapVal(remarkKey, "")
        soundDatas += res;
        if(mobileSignInputRichText){
            ckStore.setData(soundDatas);
        }
        controlVariableMap(remarkKey, soundDatas);

    }

    judgeIsRichText = () =>{
        const wfOperateStore = base.wfOperateStore;
        const { markInfo = {}} = wfOperateStore;
        const { extendParams = {}} = toJS(markInfo);
        const { mobileSignInputRichText = false} = extendParams;
        return mobileSignInputRichText;
    }

    setPanelVisible() {
      this.setState({isCheckMore : !this.state.isCheckMore});
    }

    //signPanel title
    getSignPanelTitle(isHideInput = '0') {
        const wfOperateStore = base['wfOperateStore'];
        const {markInfo = {}} = wfOperateStore;
        const signParams = toJS(markInfo);
        const {phraseInfo = []} = signParams;
        const {history, wfSignInputStore} = this.props;
        const {setCommonWords, isForwad, forwardHrmStore, forwardOperatorDatas = [], fowardSubmitParams = {}, moreSetting:{ isforwardrights}, notNeedRemind} = wfSignInputStore;
        const {forwardflag, isMulitTak} = fowardSubmitParams;

        let menuData = [];
        phraseInfo.map((item) => {
            const {workflowPhrases = '', workflowPhrasesContent = ''} = item;
            menuData.push({value: workflowPhrasesContent, label: workflowPhrases});
        });

        let userImgs = [];
        toJS(forwardOperatorDatas).map((item = {}, index) => {
            let img = item.messagerurl ? item.messagerurl : item.icon;
            if (index < 3) userImgs.push(img || '')
        });

        const { remindInfo } = this.props.wfRemindStore;
        const showRemindInfo = !_.isEmpty(remindInfo) && remindInfo.isShow === true;

        return (
            <div className='sign-panel-title'>
                {isForwad &&
                <span className='sign-userInfo' onClick={() => history.push(forwardHrmStore.path)}>
                        {
                            userImgs && toJS(userImgs).map((item = {}, index) => {
                                let leftv = index * 10;
                                return <img className={'more-user-selected'} style={{left: leftv}} src={item}/>
                            })
                        }
                    <span className='more-user' style={{left: (userImgs.length * 10)}}>
                            <Icon type={'ellipsis'}/>
                        </span>
                    </span>
                }
                 {/* 传阅,转发选项设置 */}
                 {
                   (showRemindInfo&&!notNeedRemind || (forwardflag == '1' && isforwardrights) || (forwardflag == '4') || (forwardflag == '2' && !isMulitTak)) &&  <span className='more-setting-btn'
                            ref = { ref => {this.moreSettingIcon = ref}}
                            style={{position: 'absolute', right: '15px' ,color: this.state.isCheckMore ? '#55b1f9' : '#999999', top: '12px'}}
                            onClick={() => {this.setPanelVisible()}}>
                   <Icon  type={'spread-out'} />
                  </span>
                }
                {isHideInput != '1' &&
                    <Picker data={menuData} cols={1} onOk={(v) => SignUtil.appendRemark(v)}>
                        <div className={'sign-phrase-title'}>
                            <span className={'span-title'}>{getLabel(22409, '常用批示语')}</span>
                            <Icon type="down"/>
                        </div>
                    </Picker>
                }
            </div>
        )
    }

    initEndTakOverTimeParams() {
        const {wfSignInputStore} = this.props;
        const {setForwardParams, setInquiryVariate} = wfSignInputStore;
        let val = {takOverHours: 0, takOverMins: 30, isOpenTakOvertime : '0'};
        setInquiryVariate(val)
        setForwardParams(val);
    }

    //转发设置(流程提醒、接收人权限)
    getSignSetting(){
        let arr = [];
        const { remindInfo } = this.props.wfRemindStore;
        const showRemindInfo = !_.isEmpty(remindInfo) && remindInfo.isShow === true;

        const { fowardSubmitParams = {}, moreSetting:{isforwardrights}, notNeedRemind} = this.props.wfSignInputStore;
        const {forwardflag, isMulitTak} = fowardSubmitParams;

        if(showRemindInfo&&!notNeedRemind || (forwardflag == '1' && isforwardrights) || (forwardflag == '4') || (forwardflag == '2' && !isMulitTak))
              arr.push(<RemindType isFromSignPanle={true} className="wf-forward-remind-type" isForward={true} />);
        return arr.length > 0 ? <div className="sign-panel-setting">{arr}</div> : null;
    }

    //渲染引用签字意见列表
    getRemarkQuoteCom(){
        const {wfSignInputStore} = this.props;
        const {variableMap,isForwad} = wfSignInputStore;
        const quoteDataKey = isForwad ? VariableKeys.FORWARD_SIGN_REMARK_QUOTE : VariableKeys.SIGN_REMARK_QUOTE;
        const remarkMap = SignUtil.getVariableMapVal(quoteDataKey,[]);
        let arr = [];
        remarkMap.map((value,index) => {
            const item = <div key={`quote_${index}`} className='remark_list_dom'
                              style={{position: "relative", marginLeft: "0"}}>
                <div style={{width: "100%"}}
                     dangerouslySetInnerHTML={{__html: SignUtil.quoteContentRemoveHtmlUtil(value)}}></div>
                <Icon type="cross" title={getLabel(91,"删除")}
                      style={{position: "absolute", right: "10px", top: "10px", cursor: "pointer", color: "#333"}}
                      onClick={this.deleteItem.bind(this, index)}/>
            </div>
            if (toJS(value) !== '') {
                arr.push(item)
            }
        })
        return arr;
    }

    //签字意见框
    getRemarkEditor() {
        const {wfSignInputStore} = this.props;
        const {isForwad,ckStore} = wfSignInputStore;
        const remarkKey = isForwad ? VariableKeys.FORWARD_SIGN_CONTENT : VariableKeys.SIGN_CONTENT;
        let remark = SignUtil.getVariableMapVal(remarkKey, '');
        //let toolbarOptions  =  [[{ 'header': [1, 2, 3, false] }],['bold', 'italic', 'underline','clean']];
        //const signFontSet = SignUtil.getVariableMapVal(VariableKeys.SIGN_FONT_SET,false);
        //const modules = {toolbar:signFontSet ? toolbarOptions : false};
        //f(remark == '')  remark = ' ';

        const wfOperateStore = base.wfOperateStore;
        const {markInfo = {}} = wfOperateStore;
        const signParams = toJS(markInfo);
        const {extendParams = {}} = signParams;
        const {mobileSigninputRow = 5,mobileSignInputRichText = false} = extendParams;

        const  ckConfig = {};
        if(mobileSignInputRichText) {
            ckConfig['height'] = mobileSigninputRow * 25;
        }
        remark = SignUtil.convertSpecialChar(remark);

        return (
            mobileSignInputRichText ?
                <CKRichEditor text={remark} store={ckStore} config={ckConfig} />
                :
                <TextareaItem
                    rows={mobileSigninputRow}
                    value={remark}
                    escape={true}
                    onChange={(v) => this.signInputChange(remarkKey,v)}
                    onFocus={(v)=>this.onTextareaFocus()}
                />
        )
    }

    onTextareaFocus=()=>{
        const {wfSignInputStore} = this.props;
        const {batchControlVariableMap}=wfSignInputStore;
        let updateParams = {};
        updateParams[VariableKeys.SHOW_MORE_FUN] = false;
        updateParams[VariableKeys.SIGN_VOICE_ENTRY] = false;
        updateParams[VariableKeys.SIGN_IMG_UPLOAD] = false;
        batchControlVariableMap(updateParams)
    }

    signInputChange(key,v){
        let updateParams = {};
        updateParams[key] = v;
        SignUtil.doSignInputChange(updateParams, updateParams);
    }

    //显示位置信息
    getLocationInfo() {
        const {wfSignInputStore} = this.props;
        const {variableMap, controlVariableMap, isForwad, Adapter} = wfSignInputStore;
        const key = isForwad ? VariableKeys.FORWARD_REMARK_LOCATION : VariableKeys.SIGN_REMARK_LOCATION;
        const locationInfo = SignUtil.getVariableMapVal(key, {});
        const {address = ''} = locationInfo;

        return (
            address ?
                <div className='sign-position-info'>
                    <span className='position-show'>
                        <div>
                            <Icon type={'location'}/>
                            <span className='position-detail' onClick={() => {
                                if (Adapter.judgeApiSupport(AdapterConstant.API_POSITION)) {
                                    Adapter.getLocation(locationInfo);
                                }
                            }}>{address}</span>
                            <Icon type={'cross'} onClick={() => controlVariableMap(key, {})}/>
                        </div>
                    </span>
                </div>
                :
                <span></span>
        )
    }

    getDisplayCom() {
        const {wfSignInputStore} = this.props;
        const { wfGlobalStore = {} } =  base.allStores;
        const { secLevelInfo = {},baseParam = {} } = wfGlobalStore;
        const {markInfo = {}} = base.wfOperateStore;
        const {forwardOperatorDatas, forwardHrmStore, setForwardOperators, fowardSubmitParams = {}} = wfSignInputStore;
        const {forwardflag = '1',workflowid = '',nodeid = '',bdf_wfid = '',beagenter='',f_weaver_belongto_userid='',f_weaver_belongto_usertype=''} = fowardSubmitParams;
        const {requestid = -1} = baseParam;
        let {hrmBrowser = {}} = markInfo;
        hrmBrowser = toJS(hrmBrowser);

        let dataParams = {sqlwhere : secLevelInfo.hrmSqlWhere,forwardflag:forwardflag,requestid,workflowid:workflowid,nodeid:nodeid,bdf_wfid:bdf_wfid,agentorbyagentid:beagenter,f_weaver_belongto_userid,f_weaver_belongto_usertype};
        const conditionDataParams = {...dataParams,...hrmBrowser.conditionDataParams};
        dataParams = {...dataParams,...hrmBrowser.dataParams}
        const operatorParams = this.getOperatorParams()||{}; 
        return (
            <div style={{'display': 'none'}}>
                <BrowserHrm
                    {...hrmBrowser}
                    label={getLabel(500254,"人力资源多选")} 
                    store={forwardHrmStore}
                    hasAdvanceSerach
                    isSingle={false}
                    type={1}
                    onChange={(ids, names, datas = []) => {
                        console.log("ids", ids, "datas", toJS(datas));
                        setForwardOperators(ids, toJS(datas));
                    }}
                    valueArray={forwardOperatorDatas}
                    dataParams={dataParams}
                    conditionDataParams={conditionDataParams}
                   {...operatorParams}
                />
            </div>
        )
    }

    getOperatorParams=()=>{
        const{ fwLimitInfo, fowardSubmitParams } = this.props.wfSignInputStore;
        const { isopen ='', choiceoperator = '' } = fwLimitInfo;
        const{ forwardflag='1' } = fowardSubmitParams;
        const { wfGlobalStore } = base.allStores;
        const { baseParam = {} } = wfGlobalStore;
        const { requestid } = baseParam;
        let operatorParams={};
        const defaultTabs  = [
            { name: getLabel(31786, '流程参与人'), key: '8' },
            { name: getLabel(24515, '最近'), key: '1' },
            { name: getLabel(18511, '同部门'), key: '2' },
            { name: getLabel(15089, '我的下属'), key: '3' },
            { name: getLabel(16455, '组织结构'), key: '4' },
            { name: getLabel(81554, '常用组'), key: '5' },
            { name: getLabel(1340, '所有人'), key: '6' },
        ]
        let hideTab8 = (isopen == -1 && choiceoperator== -1)|| (isopen == 1 && choiceoperator != 1);
        if(forwardflag != "3" && !hideTab8){
            operatorParams = {
                hasDing:true,
                dingUrl:"/api/workflow/forward/getReqWfNodeOperators",
                dingParams:{
                    requestid,
                    isFromEMBrow:1,
                    isDistinct:0
                },
                tabs:defaultTabs,
                tabsProps:{initialPage:"8"}
            }
        }
        return operatorParams;
    }

    getImgUploadCom() {
        const {wfSignInputStore} = this.props;
        const {isForwad} = wfSignInputStore;
        //annexdocinfos
        const imgKey = isForwad ? VariableKeys.FORWARD_SIGN_IMAGE : VariableKeys.SIGN_IMAGE;
        let imgages = SignUtil.getVariableMapVal(imgKey, []);

        const wfOperateStore = base.wfOperateStore;
        const {markInfo = {}} = wfOperateStore;
        const {annexmainId, annexsubId, annexsecId = '', annexmaxUploadImageSize} = markInfo;
        const category = `${annexmainId},${annexsubId},${annexsecId}`;
        return (
            <div className={'wf-sign-img-list'}>
                <Upload
                    datas={imgages}
                    listType="img"
                    uploadParams={{category}}
                    uploadUrl={'/api/doc/upload/uploadFile'}
                    onUploading={(type)=>SignUtil.onUploading(type,'imglist')}
                    onChange={(ids, datas) => {
                        let variableParams = {};
                        variableParams[imgKey] = datas;
                        SignUtil.doSignInputChange({}, variableParams);
                    }}
                    limitType="jpg,jpeg,png"
                />
            </div>
        )
    }

    onWrapTouchStart = (e) => {
        // fix touch to scroll background page on iOS
        if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
            return;
        }
        const pNode = closest(e.target, '.am-modal-content');
        if (!pNode) {
            e.preventDefault();
        }
    }

    deleteItem(key) {
        const {wfSignInputStore} = this.props;
        const {controlVariableMap,isForwad} = wfSignInputStore;
        const quoteDataKey = isForwad ? VariableKeys.FORWARD_SIGN_REMARK_QUOTE : VariableKeys.SIGN_REMARK_QUOTE;
        let quoteData = SignUtil.getVariableMapVal(quoteDataKey,[]);
        let _quoteData = quoteData.filter((item,index)=> index !== key);
        controlVariableMap(quoteDataKey,_quoteData);
    }
}

function closest(el, selector) {
    const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    while (el) {
        if (matchesSelector.call(el, selector)) {
            return el;
        }
        el = el.parentElement;
    }
    return null;
}

export default SignActionPanel;